class LinkNode {
    static create(data) {
        if (data instanceof LinkNode) return data;
        return new LinkNode(data);
    }

    pre: LinkNode = null as any;
    next: LinkNode = null as any;
    key = '';
    constructor(public data: any) {
        if (data instanceof LinkNode) return data;
        this.key = data?.key || Math.random();
    }
}
export class LinkList {
    size = 0;
    head: LinkNode = null as any;
    current: LinkNode = null as any;
    ended = false;
    add(node) {
        if (this.ended) return;
        node = new LinkNode(node);

        if (!this.head) {
            this.head = node;
        } else {
            node.pre = this.current;
            node.pre.next = node;
        }
        this.current = node;

        this.size += 1;
        return node;
    }

    append(key, data) {
        const insert_node = this.get(key)!;
        const node = new LinkNode(data);
        node.next = insert_node.next;
        node.pre = insert_node;
        insert_node.next = node;
        return node;
    }

    find(callback) {
        let node = this.head as any as LinkNode;
        while (node) {
            if (callback(node)) {
                return node;
            }
            node = node.next;
        }
    }

    get(key) {
        const item = this.find((node) => node.key === key && node) as any as LinkNode;
        return item;
    }

    end() {
        if (!this.head || !this.current) return;
        this.current.next = this.head;
        this.head.pre = this.current;
        this.ended = true;
    }
}
